package Servlets;

import Beans.User;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.file.Files;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 @author chuck
 */
@WebServlet("/images/userPictures/*")
public class ImageServlet extends HttpServlet {

  private String imagePath;

  @Override
  public void init() throws ServletException {
    this.imagePath = "/awesome-dates/userPictures/";
    //TODO remove when everyone has the folders built
    File file = new File("C:\\awesome-dates\\userPictures");
    if (!file.exists()) {
      if (file.mkdirs()) {
        System.out.println("DEBUG: Directory is created!");
      } else {
        System.out.println("DEBUG: Failed to create directory!");
      }
    }
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String requestedImage = request.getPathInfo();
    if (requestedImage == null) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }
    if (requestedImage.contains(User.DEFAULT_PROFILE_PICTURE)) {
      requestedImage = "/" + User.DEFAULT_PROFILE_PICTURE;
    }
    File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));
    if (!image.exists()) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }
    String contentType = getServletContext().getMimeType(image.getName());
    if (contentType == null || !contentType.startsWith("image")) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }
    response.reset();
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(image.length()));
    Files.copy(image.toPath(), response.getOutputStream());
  }
}
